package com.keydom.ropeskipping.utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.cert.CertificateException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.X509TrustManager;


/**
 * send http request.
 *
 * @author : PengQiang
 * @date :  2024/5/14
 **/
public class HttpRequestUtil {
    //定义一个信任所有证书的TrustManager
    public static X509TrustManager trustAllCert = new X509TrustManager() {
        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[]{};
        }
    };

    public static HttpConnResponse sendPostRequest(String url, String jsonInputString, Map<String, String> headers) throws IOException {
        URL obj = new URL(url);
        HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
        // 设置请求方法为 POST
        con.setRequestMethod("POST");
        con.setSSLSocketFactory(new SSL(trustAllCert));

        // 设置请求头部信息
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("Accept", "application/json");

        for (String key : headers.keySet()) {
            con.setRequestProperty(key, headers.get(key));
        }
        // 启用输出流，以便向服务器发送请求体
        con.setDoOutput(true);

        // 创建一个输出流写入请求体数据
        try (DataOutputStream wr = new DataOutputStream(con.getOutputStream())) {
            wr.writeBytes(jsonInputString);
            wr.flush();
        }

        // 获取响应状态码
        int responseCode = con.getResponseCode();
        HttpConnResponse response = new HttpConnResponse();
        response.setCode(responseCode);

        // 读取响应内容
        byte[] responseBytes = readResponse(con.getInputStream());
        try {
            String responseBody = new String(responseBytes, "UTF-8");
            response.setBody(responseBody);
        } catch (Exception e) {
            response.setErrorMsg(e.toString());
            e.printStackTrace();
        }

        return response;
    }

    private static byte[] readResponse(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int bytesRead;
        ByteArrayOutputStream responseBuffer = new ByteArrayOutputStream();

        while ((bytesRead = inputStream.read(buffer)) != -1) {
            responseBuffer.write(buffer, 0, bytesRead);
        }

        return responseBuffer.toByteArray();
    }

    public static Map<String, Object> jsonToMap(String jsonString) {
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            Iterator<String> keys = jsonObject.keys();

            Map<String, Object> map = new HashMap<>();
            while (keys.hasNext()) {
                String key = keys.next();
                map.put(key, jsonObject.get(key));
            }
            return map;
        } catch (JSONException e) {
            return null;
        }
    }
}
